<template>
	<div id="">
		<el-dialog v-loading="loading" title="编辑角色" :visible.sync="dialogVisible" @close='closeDialog'>
		  <el-form :model="form" :rules="rules" ref="form">
		    <el-form-item label="角色名称" prop="name" :label-width="formLabelWidth">
		      <el-input placeholder="请输入角色名称"  size='small' v-model="form.name" autocomplete="off"></el-input>
		    </el-form-item>
			<el-form-item label="选择权限" prop="access" :label-width="formLabelWidth">
				<el-tree
				  :data="list"
				
				  show-checkbox
				  default-expand-all
				  node-key="id"
				  ref="tree"
				  highlight-current
				  @check="changeAccess"
				  :props=" {
					  children: 'children',
					  label: 'name'
					}">
				</el-tree>
			</el-form-item>

			<el-form-item label="排序" :label-width="formLabelWidth">
			  <el-input   size='small' v-model="form.sort" autocomplete="off"></el-input>
			</el-form-item>
		  </el-form>
		  <div slot="footer" class="dialog-footer">
		    <el-button @click="closeDialog">取 消</el-button>
		    <el-button type="primary" @click="SubmitForm">确 定</el-button>
		  </div>
		</el-dialog>
	</div>
</template>

<script>
		import AuthApi from '@/api/auth.js'
		import RoleApi from '@/api/role.js'
		export default {

		    data() {
		      return {
			
				loading: true,				  
				// 规则
				rules: {
				  name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
				  access:[{ required: true, message: '请选择权限', trigger: 'blur' }]
				},
				dialogVisible: false,
				
		        form: {
				  id:'',
		          name: '',
				  access:[],
				  sort:'1',
		        },
				list:[],
		        formLabelWidth: '120px'
		      };
		    },

			created() {
			  this.dialogVisible = this.$parent.editVisible;
			  this.form.id = this.$parent.row_id;
			  let param = {'id':this.form.id}
			  
			  // 获取全部权限
			  AuthApi.getAccessList().then((res)=>{
			  	this.list = res.data.data
			  })
			  // 获取该角色名称与权限
			  RoleApi.getRoleById(param).then((res)=>{
					this.$refs.tree.setCheckedKeys(res.data.data.leaf);
					this.form.name = res.data.data.name
					this.form.sort = res.data.data.sort
					this.form.access = res.data.data.access
					this.loading = false
			  })
		

			},
			methods:{
				changeAccess(v1,v2){
					let access = []
					this.form.access = access.concat(v2.halfCheckedKeys,v2.checkedKeys)
				},
				SubmitForm(){
				
				let params = this.form
				this.$refs.form.validate((valid) => {
					if(valid){

						RoleApi.edit(params).then((res) => {

						let type = res.data.code == 1?'success':'error';	
						this.$message({
						  message: res.data.msg,
						  type: type
						});
						this.closeDialog();
						this.$router.go(0)
						}).catch((error) => {
							
						
						});	
					}

				})
				},
				closeDialog(){

					this.$emit('handleClick',false)
				}
			}
		  };
</script>

<style scoped>
	/deep/.el-form-item__content {
	    display: block;
	    align-items: center;
	}
	.el-form-item {
	    margin-bottom: 16px;
	}
</style>
